iOS system
iOS version检测
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
if (SYSTEM_VERSION_LESS_THAN(@"8.0")) {
...
}
文件保存数据库的问题
iOS 往数据库里写保存文件路径的时候,不要写全路径,因为软件更新或者重新安装沙盒路径会变
更新的流程是这样的:更新时,先在新的路径里安装新程序,然后把旧程序文件夹里的配置文件之类的文件拷贝到新的路径里去,然后删除旧程序
所以,如果数据库里保存的是绝对路径,那么软件会找不到文件。所以要保存相对路径。比如/var/mobile/Applications/ECDD1B2D-E53D-4914-BDDB-F0578BADAA38/Documents/A/B/C/9A4613EA-232A-480C-9492-B34A00BE3CB6.txt
只写/A/B/C/9A4613EA-232A-480C-9492-B34A00BE3CB6.txt就好,前半部分用系统方法获取。
保存图片至iPhone图库
UIImageWriteToSavedPhotosAlbum(UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo);
NSString
NSString 和 std::string 相互转换
//NSString to string
NSString *strA = @"NSString";
std::string *strB = new std::string([strA UTF8String]);
//or
std::string strB([strA UTF8String]);
//string to NSString
NSString *str = [NSString stringWithCString:string.c_str()
encoding:[NSString defaultCStringEncoding]];
NSString *str = [NSString stringWithCString:string.c_str()
encoding:NSUTF8StringEncoding]; // for chinese
std::string param; // <-- input
NSString* result = [NSString stringWithUTF8String:param.c_str()];
NSString* alternative = [[NSString alloc] initWithUTF8String:param.c_str()];
//chinese
[NSString stringWithCString:m_AnswerSheet.GetName().c_str() encoding:NSUTF8StringEncoding]
NSString实现trimRight方法
//该方法会删除string两端的空格
NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//若要只删除string结尾的空格 写一个NSString拓展类 添加如下方法
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
for (length; length > 0; length--) {
if (![characterSet characterIsMember:charBuffer[length - 1]]) {
break;
}
}
return [self substringWithRange:NSMakeRange(location, length - location)];
}
//然后调用
NSString *trimmedString = [yourString stringByTrimmingTrailingCharactersInSet:[NSCharacterset whitespaceAndNewlineCharacterSet]];
NSString后连接字符串
string = [NSString initWithFormat:@"%@,%@", string1, string2 ];
string = [string1 stringByAppendingString:string2];
string = [string stringByAppendingFormat:@"%@,%@",string1, string2];
NSString,Char,ASCII转换
//char to int ASCII-code
char c = 'a';
int ascii_code = (int)c;
//int to char
int i = 65; // A
c = (char)i;
// NSString to ASCII
NSString *string = @"A";
int asciiCode = [string characterAtIndex:0]; // 65
// ASCII to NSString
int asciiCode = 65;
NSString *string = [NSString stringWithFormat:@"%c", asciiCode]; // A
char myChar = 'r';
NSString* string = [NSString stringWithFormat:@"%c" , myChar];
NSString文字高度
cocoa获取UUID
NSString CHelpFunction::stringWithUuid() {
CFUUIDRef uuidObj = CFUUIDCreate(nil);
NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(nil, uuidObj));
CFRelease(uuidObj);
return uuidString;
}
UIView
UIView贴背景图
UIView只有setBackgroundColor
,就用它来设置
UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
[myLabel setBackgroundColor:color];
UIView添加点击事件
参考:reference
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
singleTap.numberOfTapsRequired = 1;
[preArrowImage setUserInteractionEnabled:YES];
[preArrowImage addGestureRecognizer:singleTap];
-(void)tapDetected{
NSLog(@"single Tap on imageview");
}
获取UIView触摸点
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
NSLog(@"x:%f, y:%f", point.x, point.y);
if (!CGRectContainsPoint(centerView.frame, point)) {
[self removeFromSuperview];
}
}
layoutSubviews调用时机
init
:不会调用layoutSubviews
addSubview:
:被添加的view1、调用这个方法的view2、view2的所有子view都会调用layoutSubviews
setFrame
:只有在view设置frame且尺寸参数有不同的情况下调用- 滑动
UIScrollView
时,scrollView和其父view会调用 - 旋转屏幕会在viewController的根view调用
- 重新改变view的大小,其父view会调用
drawInRect: withAttributes:的参数怎么写
UIFont *textFont = [UIFont fontWithName: @"Helvetica" size: 60];
UIColor *textColor = [UIColor blackColor];
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentCenter;
[textContent drawInRect:textRect withAttributes:@{NSFontAttributeName:textFont, NSForegroundColorAttributeName:textColor, NSParagraphStyleAttributeName:textStyle}];
设置粗体文字
首先可以上这个网站:http://iosfonts.com/查看自己要用的字体是否支持粗体,然后使用下面方法
-(void)boldFontForLabel:(UILabel *)label{ UIFont *currentFont = label.font; UIFont *newFont = [UIFont fontWithName:[NSString stringWithFormat:@"%@-Bold",currentFont.fontName] size:currentFont.pointSize]; label.font = newFont; }
UIView一些尺寸属性
- frame:origin是相对于屏幕的点的坐标,size就是其尺寸
- bound: origin永远是(0,0),size也是尺寸
- center: 是View的中心点,但坐标是相对于屏幕的。如果需要相对自己的中心点,则需要用bound.origin来计算
UIView加外边框
CGFloat borderWidth = 2.0f;
self.frame = CGRectInset(self.frame, -borderWidth, -borderWidth);
self.layer.borderColor = [UIColor yellowColor].CGColor;
self.layer.borderWidth = borderWidth;
UIView切换动画
只要提供View的初识状态和结束状态,然后交给showAnimation来做即可
-(void)showAnimation {
[self.view addSubview:geopointView]
geopointView.frame = // somewhere offscreen, in the direction you want it to appear from
[UIView animateWithDuration:10.0
animations:^{
geopointView.frame = // its final location
}];
}
UIView滑入动画
[UIView transitionFromView:viewToReplace
toView:replacementView
duration:1
options:UIViewAnimationOptionTransitionFlipFromBottom
completion:nil];
判断一个点在UIView里
CGPoint locationInView = [imageView convertPoint:point fromView:imageView.window];
if ( CGRectContainsPoint(imageView.bounds, locationInView) ) {
// Point lies inside the bounds.
}
UIView调用presentViewController
自动布局下获取View的尺寸
把touch事件传递给子View
涉及到事件传递部分内容,另外再开博客记录
reference
UILabel
UILabel设置行间距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = spacing;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];
label.attributedText = attributedString;
UILabel下划线
NSDictionary *underlineAttribute = @{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
myLabel.attributedText = [[NSAttributedString alloc] initWithString:@"Test string"
attributes:underlineAttribute];
UIButton
模拟按钮点击事件
[buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside];
UIImage & UIImageView
用纯色生成一个UIImage
@implementation UIButton (ButtonMagic)
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
[self setBackgroundImage:[UIButton imageFromColor:backgroundColor] forState:state];
}
+ (UIImage *)imageFromColor:(UIColor *)color {
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
UIImage占内存大小
NSUInteger size = CGImageGetHeight(thumbImage.CGImage) * CGImageGetBytesPerRow(thumbImage.CGImage);
UIImage加边框
把UIView生成UIImage
UIColor
给ClearColor添加alpha
- (void)setBackgroundColor:(UIColor *)color
{
self.backgroundColor = [color colorWithAlphaComponent:0.3f];
}
NSNotification
NSNotification流程
//send
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
NSDictionary *d = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:m_index] forKey:@"index"];
[nc postNotificationName:@"viewClicked" object:self userInfo:d];
//regist observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewClickAt:) name:@"quesViewClicked" object:nil];
//do function
- (void)quesViewClickAt:(NSNotification *)noti {
int index = [[[noti userInfo] objectForKey:@"index"] intValue];
}
//dealloc
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
UITextView & UITextField
keyboard强行关闭
[view endEditing:YES];
UITextView限制输入字符
- (BOOL)textView:(nonnull UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(nonnull NSString *)text {
// Prevent crashing undo bug
if(range.length + range.location > textView.text.length)
{
return NO;
}
NSUInteger newLength = [textView.text length] + [text length] - range.length;
return newLength <= 1024;
}
UITextView添加默认文字
UITextField是有placeholder(?)这个属性的,但是UITextView没有,大家表示也是醉了。
reference
- (void)textViewDidBeginEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@"placeholder text here..."]) {
textView.text = @"";
textView.textColor = [UIColor blackColor]; //optional
}
[textView becomeFirstResponder];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@""]) {
textView.text = @"placeholder text here...";
textView.textColor = [UIColor lightGrayColor]; //optional
}
[textView resignFirstResponder];
}
UITextField光标距离左边间隔太小
UITextField *content = ......;
//设置输入左边距
CGRect frame = content.frame;
frame.size.width = 5;
UIView *leftView = [[UIView alloc] initWithFrame:frame];
content.leftViewMode = UITextFieldViewModeAlways;
content.leftView = leftView;
UITextField下划线
CALayer *border = [CALayer layer];
CGFloat borderWidth = 2;
border.borderColor = [UIColor darkGrayColor].CGColor;
border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, textField.frame.size.height);
border.borderWidth = borderWidth;
[textField.layer addSublayer:border];
textField.layer.masksToBounds = YES;
UITextField内容改变事件
UITextView有对应的回调,UITextField就没有。
reference
reference2
[myTextField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
多个UITextField,键盘return改为next->next->done (iOS9又有新的类型)
//set keyboard
if (i == count - 1)
[contentText setReturnKeyType:UIReturnKeyDone];
else
[contentText setReturnKeyType:UIReturnKeyNext];
#pragma mark - TextFieldDelegate
- (BOOL)textFieldShouldReturn:(nonnull UITextField *)textField {
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
UIScrollView & UITableView & UICollectionView
UIScrollView滚动到顶端
//UPDATE FOR iOS 7
[self.scrollView setContentOffset:
CGPointMake(0, -self.scrollView.contentInset.top) animated:YES];
//ORIGINAL
[self.scrollView setContentOffset:CGPointZero animated:YES];
//or if you want to preserve the horizontal scroll position and just reset the vertical position:
[self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0) animated:YES];
UITableView屏蔽自动滚动效果
reference
继承UITableViewController重写
- (void)viewWillAppear:(BOOL)animated { //不调用super方法 屏蔽自动滚动
//[super ...];
}
判断UITableViewCell是否可见
-(BOOL)isRowZeroVisible {
NSArray *indexes = [tableView indexPathsForVisibleRows];
for (NSIndexPath *index in indexes) {
if (index.row == 0) {
return YES;
}
}
return NO;
}
UICollectionViewCell构造
UICollectionViewCell 不能用-(id)init{}
,要用-(id)initWithFrame:(CGRect)frame
或者initWithCoder()
NSArray & NSDictionary
NSArray和std::vector转换
std::vector strVec;
for (int i = 0; i < [NSMutableArrayObject count]; i++) {
NSString *NS_Ans = (NSString *)[NSMutableArrayObject objectAtIndex:i];
std::string Str_Ans = *new std::string([NS_Ans UTF8String]);
strVec.push_back(Str_Ans);
}
return strVec;
//
std::vector ansArray = getOneVector();
NSMutableArray *nsArray = [NSMutableArray array];
for (int j = 0; j < ansArray.size(); j++) {
NSString *item = [NSString stringWithCString:ansArray[j].c_str() encoding:[NSString defaultCStringEncoding]];
[nsArray addObject:item];
}
return ansArray;
NSArray添加CGPoint对象
一般使用NSValue reference
NSArray *points = [NSArray arrayWithObjects:
[NSValue valueWithCGPoint:CGPointMake(5.5, 6.6)],
[NSValue valueWithCGPoint:CGPointMake(7.7, 8.8)],
nil];
NSValue *val = [points objectAtIndex:0];
CGPoint p = [val CGPointValue];
NSMutableArray/NSMutableDictionary插入空值
if ((NSNull *)[mPages objectAtIndex:showPos] == [NSNull null]) {
[mPages removeObjectAtIndex:showPos];
}
[mPages insertObject:mPage atIndex:showPos];
[mPages removeObjectAtIndex:hidePos];
[mPages insertObject:[NSNull null] atIndex:hidePos];
NSDictionary保存int
类型
NSDictionary保存的都是对象,所以int
要转成NSNumber
//save
[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:m_quesIndex] forKey:@"index"];
//get
i = [[dic objectForKey:@"index"] intValue];
其他
Cocoapods pod install 太慢
pod install --verbose --no-repo-update
标注代码段
reference
在OC里经常用
#pragma mark - xxxx
来分隔代码
Swift里用的是
// MARK: - xxx